package com.hsnn.medstgmini.crypto;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.SecretKeyEntry;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;

/**
 * @category key 存储
 * @author 单大伟
 * @date 2015-08-30
 */
public class KeyStoreUtil {

	private static final Logger log = Logger.getLogger(KeyStoreUtil.class);
	
//    @Value("#{sysProp['system.keystore.filepath']}")
//    private static String keystorePath;
    
	/**
	 * @category Keystore文件是否存在
	 * @author 单大伟
	 * @date 2015-08-30
	 * @filePath 文件路径
	 * @return boolean true:存在, false:不存在
	 */
	public static boolean keyStoreExits(String filePath) {
		File keyStoreFile = new File(filePath);
		log.info("key store exists = " + keyStoreFile.exists());
		return keyStoreFile.exists();
		
	}

	/**
	 * @category 取出密码
	 * @author 单大伟
	 * @date 2015-08-30
	 * @filePath 文件路径
	 * @password keystore密码
	 * @keyAliaas 密码别名
	 * @return SecretKey
	 */
	public static SecretKey getSecretKey(String filePath, String password, String keyAlias) throws KeyStoreException, 
																							  NoSuchAlgorithmException, 
																							  CertificateException, 
																							  IOException, 
																							  UnrecoverableEntryException {
    	KeyStore ks = KeyStore.getInstance("JCEKS");
    	char[] pwd = password.toCharArray();
		FileInputStream fis = new FileInputStream(filePath);
		ks.load(fis, pwd);
		SecretKeyEntry pkEntry = (SecretKeyEntry) ks.getEntry(keyAlias,  new PasswordProtection(pwd));
		SecretKey mySecretKey = (SecretKey) pkEntry.getSecretKey();
		return mySecretKey;
	}
	
	/**
	 * @category 设置密码，注意：一般不要调用
	 * @author 单大伟
	 * @date 2015-08-30
	 * @filePath 文件路径
	 * @password keystore密码
	 * @keyAliaas 密码别名
	 * @keySpec
	 * @return void
	 */
	public static void setupSecretKey(String filePath, String password, String keyAlias, String keySpec) 
			                                                                             throws KeyStoreException, 
	                                                                                            NoSuchAlgorithmException, 
	                                                                                            CertificateException, 
	                                                                                            IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {	                                                                                             
			KeyStore ks = KeyStore.getInstance("JCEKS");
			fis = new FileInputStream(filePath);
			ks.load(fis, password.toCharArray());
			
			SecretKey secretKey = new SecretKeySpec(keySpec.getBytes(), "DESede");
		    SecretKeyEntry skEntry = new SecretKeyEntry(secretKey);
		    
			ks.setEntry(keyAlias, skEntry, new PasswordProtection(password.toCharArray()));
			fos = new FileOutputStream(filePath);
			ks.store(fos, password.toCharArray());
		
        } finally {
        	if (fis != null) {
        	    fis.close();
        	}
        	
        	if (fos != null) {
        	    fos.close();
        	}
        }
	}
}